<?php

namespace App\Repository\Rebate;

use App\Libs\PhpOffice\Excel;
use App\Models\Order\OrderMoreModel;
use App\Models\Orders\OrdersModel;
use App\Models\Orders\OrdersUserModel;
use App\Models\Rebate\RebateLogsModel as Model;
use App\Repository\BaseRepository;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class RebateLogsRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new Model();
        $this->log = new Logger('RebateLogs');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/RebateLogs.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    //列表
    public function index($params, $page = 1, $limit = 10)
    {
        $where = [];
        if (isset($params['ordersno']) && !empty($params['ordersno'])) {
            $where['eq']['a.ordersno'] = trim($params['ordersno']);
        }
        if (isset($params['product_id']) && !empty($params['product_id'])) {
            $where['eq']['a.product_id'] = trim($params['product_id']);
        }
        if (isset($params['phone']) && !empty($params['phone'])) {
            $where['eq']['a.phone'] = trim($params['phone']);
        }
        if (isset($params['dateRange']) && !empty($params['dateRange'])) {
            $time = $params['dateRange'];
            $where['between'] = ['a.rebate_at' => [$time]];
        }
        //        先要总数
        $totalRows = 0;
        if ($page == 1) {
            $totalRows = $this->model->from($this->model->getTable() . ' AS a')->searchWhere($where)->count('a.id');
        }
        $ModelOrders = new OrdersModel();
        $ModelOrdersUser = new OrdersUserModel();
        $fields = ['a.id', 'a.money', 'a.customer_name', 'a.phone', 'a.month', 'a.type', 'a.rebate_at',
            'b.ordersno', 'b.product_name', 'b.product_id', 'b.goods_name', 'b.goods_code', 'b.created_at', 'b.status', 'b.iccid', 'b.first_status_at', 'b.first_status', 'b.is_online',
            'c.sku_number', 'c.contact_name'
        ];
        $rows = $this->model->from($this->model->getTable() . ' AS a')
            ->leftJoin($ModelOrders->getTable() . ' AS b', 'a.ordersno', '=', 'b.ordersno')
            ->leftJoin($ModelOrdersUser->getTable() . ' AS c', 'a.ordersno', '=', 'c.orderno')
            ->searchWhere($where)
            ->select($fields)
            ->page($page, $limit)->orderByDesc('id')->get();
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

    //修改
    public function edit($params = [])
    {
        $mustField = [
            'id' => '数据编号不能没有',
            'money' => '金额不能为空',
            'rebate_at' => '返费日期不能为空'
        ];
        $optionalFields = $this->model->getTableField();
        $updateData = $this->getRealData($params, array_keys($mustField), $optionalFields, $mustField);
        if (!empty($updateData) && is_string($updateData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $updateData
            );
        }
        $id = $updateData['id'];
        $oldRow = $this->model->where(['id' => $id])->select(['type', 'first_at'])->first();
        $updateData['month'] = $this->computeT($oldRow['first_at'], $updateData['rebate_at']);
        $updateData['created_by'] = $params['user']['id'];
        unset($updateData['id']);
        $res = $this->model->where(['id' => $id])->update($updateData);
        if (false !== $res) {
            return $this->returnMsg(200, '修改成功');
        } else {
            return $this->returnMsg(20, '修改错误');
        }
    }

    public function computeT($firstAt, $rebateAt)
    {
        if (!is_numeric($firstAt)) {
            $firstAt = strtotime($firstAt);
        }
        if (!is_numeric($rebateAt)) {
            $rebateAt = strtotime($rebateAt);
        }
        $diffY = date('Y', $rebateAt) - date('Y', $firstAt);
        $diffM = date('m', $rebateAt) - date('m', $firstAt);
        return abs($diffY * 12 + $diffM);
    }

//   订单返费信息
    public function importData($moreFileId)
    {
        // 查询出来上传的文件
        $ModelMoreFile = new OrderMoreModel();
        $moreFileData = $ModelMoreFile->where(['id' => $moreFileId, 'is_run' => 0, 'type' => 'importRebate'])->first();
        if (!$moreFileData) {
            return $this->returnMsg(1, '未查询到文件' . $moreFileId);
        }
        $shopId = $moreFileData->shop_id;
        $upFile = $moreFileData->upload_rout;
        $upFile = public_path($upFile);
        if (empty($upFile) || !file_exists($upFile)) {
            return $this->returnMsg(100, '文件不存在:' . $upFile);
        }
        if (empty($shopId)) {
            return $this->returnMsg(103, '店铺id 不存在');
        }
        $createdUserId = $moreFileData->created_by;
        $excelClient = new Excel();
        $importData = $excelClient->importFile($upFile, ['ordersno', 'phone', 'customer_name', 'money', 'rebate_at', 'type'], function ($data) use ($createdUserId) {
            $data['ordersno'] = trim($data['ordersno'] ?? '');
            $data['money'] = floatval($data['money'] ?? 0);
            $data['type'] = intval($data['type']);
            $data['created_by'] = $createdUserId;
            if (!empty($data['rebate_at'])) {
                if (is_numeric($data['rebate_at'])) {
                    $data['rebate_at'] = date('Y-m-d H:i:s', ($data['rebate_at'] - 25569) * 3600 * 24);
                } else if (is_string($data['rebate_at'])) {
                    $data['rebate_at'] = date('Y-m-d H:i:s', strtotime(trim($data['rebate_at'])));
                }
            }
            return $data;
        });
        $successNum = 0;
        $failNum = 0;
        if (empty($importData['data'])) {
            return $this->returnMsg(2, '文件无数据');
        }
        $ModelOrders = new OrdersModel();
        foreach (array_chunk($importData['data'], 100, true) as $key => $rows) {
            // 订单信息
            $ordersNos = [];
            foreach ($rows as $ni => $nv) {
                $ordersNos[] = $nv['ordersno'];
            }
            // 查询订单信息
            $ordersNos = array_unique($ordersNos);
            if (!empty($ordersNos)) {
                $where = [];
                $where['in']['ordersno'] = $ordersNos;

                $ordersRows = [];
                foreach ($ModelOrders->searchWhere($where)->select(['id', 'ordersno', 'product_id', 'first_status', 'first_status_at'])->cursor() as $orderRow) {
                    $ordersRows[$orderRow->ordersno] = $orderRow;
                }
                $md5sumKeys = [];
                $nowRows = [];
                foreach ($rows as $row) {
                    $ordersno = $row['ordersno'];
                    $orderRow = $ordersRows[$ordersno];

                    $row['orders_id'] = $orderRow->id;
                    $row['product_id'] = $orderRow->product_id;
                    $row['first_at'] = $orderRow->first_status_at;
                    // 第几个月返
                    $row['month'] = -1;
                    if ($row['type'] == 0) {
                        $row['month'] = 0;
                    } else if (!empty($row['rebate_at']) && !empty($orderRow->first_status_at)) {

                        $row['month'] = $this->computeT($orderRow->first_status_at, $row['rebate_at']);
                    }
//                    $md5sum = md5($orderRow->ordersno . $row['type'] . $row['month']);
//                    $md5sumKeys[] = $md5sum;
//                    $row['md5sum'] = $md5sum;
//                    $nowRows[$md5sum] = $row;
                    $nowRows[] = $row;
                }
                $this->model->insert($nowRows);
                $successNum += count($nowRows);
//                if (!empty($md5sumKeys)) {
//                    $newAddRows = [];
//                    $willUpdateData = [];
//                    $where = [];
//                    $where['in']['md5sum'] = $md5sumKeys;
//                    foreach ($this->model->searchWhere($where)->select(['id', 'ordersno'])->cursor() as $rebateRow) {
//                        $willUpdateData[$rebateRow->ordersno] = $rebateRow->id;
//                    }
//                    foreach ($nowRows as $nk => $nv) {
//                        if ($nv['month'] < 0 || empty($nv['first_at']) || empty($nv['rebate_at'])) {
//                            $failNum += 1;
//                        } else {
//                            $successNum += 1;
//                            if (isset($willUpdateData[$nv['ordersno']])) {
//                                $this->model->where(['id' => $willUpdateData[$nv['ordersno']]])->update($nv);
//                            } else {
//                                $newAddRows[] = $nv;
//                            }
//                        }
//                    }
//                    if (!empty($newAddRows)) {
//                        $this->model->insert($newAddRows);
//                    }
//                }
            }
        }
        $ModelMoreFile->where(['id' => $moreFileData['id']])->update(['is_run' => 1, 'fail_num' => $failNum, 'success_num' => $successNum]);
        return $this->returnMsg(200, '文件处理完成');
    }
}
